<template>
    <el-dialog :title="title" :visible.sync="dialogForm" width="800px">
        <el-form :inline="true" :model="form" ref="form" v-loading="loading" class="search-form" :rules="rules"
                 label-width="120px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="计件规则名称：" prop="feeRuleName">
                        <el-input v-model="form.feeRuleName"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属单位：">
                        <el-input v-model="form.orgName" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="业务模式：" prop="businessModule">
                        <el-select v-model="form.businessModule" @change="handleChangeModule" placeholder="请选择"
                                   clearable>
                            <el-option v-for="[key, val] in _dictBusinessModule" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <!--<el-form-item label="计件标准：">-->
                        <!--基本标准-->
                    <!--</el-form-item>-->
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="计件指标：" prop="feeUnit">
                        <el-select v-model="form.feeUnit" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictFeeUnit" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!--<el-col :span="12">-->
                    <!--<el-form-item label="计件方式：">-->
                        <!--<el-select v-model="form.businessModule" @change="handleChangeModule" placeholder="请选择"-->
                                   <!--clearable>-->
                            <!--<el-option v-for="[key, val] in _dictBusinessModule" :key="key" :label="val" :value="key">-->
                            <!--</el-option>-->
                        <!--</el-select>-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="计件条件：" prop="feeRule">
                        <div v-for="(item,index) in form.feeRule" :key="index">
                            <el-select v-model="item.code" style="width: 120px"
                                       placeholder="请选择" clearable>
                                <el-option v-for="rule in ruleList" :key="rule.code" :label="rule.name"
                                           :value="rule.code">
                                </el-option>
                            </el-select>
                            <el-select v-model="item.operator" @change="handleChangeOp(item,index)" style="width: 120px"
                                       placeholder="请选择" clearable>
                                <el-option v-for="[key, val] in _dictRuleOperator" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>
                            <el-tooltip v-if="item.ruleDataType!=='TEXT'&&isClick" :disabled="item.operator!=='in'&&item.operator!=='nIn'"
                                        class="item" effect="dark" :content="getContent(item)" placement="top">
                                <el-select v-model="item.typeValue"
                                           @focus="handleChangeCode(item)"
                                           placeholder="请选择"
                                           :multiple="item.operator==='in'||item.operator==='nIn'"
                                           :collapse-tags="item.operator==='in'||item.operator==='nIn'"
                                           :disabled="!item.code"
                                           clearable>
                                    <el-option v-for="rule in item.dataSource" :key="rule.code" :label="rule.name"
                                               :value="rule.code">
                                    </el-option>
                                </el-select>
                            </el-tooltip>

                            <el-input style="width: 188px" v-if="item.ruleDataType==='TEXT'"></el-input>
                            <el-select v-model="item.isExistSub" style="width: 120px" placeholder="请选择" clearable>
                                <el-option v-for="[key, val] in _dictRuleConnect" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>
                            <el-button v-if="index===form.feeRule.length-1"
                                       @click="form.feeRule.push({ code: '', operator: '', typeValue: '', dataSource: [], ruleDataType: '',isExistSub:'AND' })"
                                       type="text" icon="el-icon-plus" size="medium"></el-button>
                            <el-button v-if="index!==form.feeRule.length&&form.feeRule.length>1"
                                       @click="form.feeRule.splice(index,1)"
                                       type="text" icon="el-icon-close" style="color: red" size="medium"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="计件规则描述：">
                        <el-input type="textarea" :rows="3" style="width: 570px" :maxLength="255" placeholder="请输入内容"
                                  v-model="form.feeRuleDesc"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="费率影响因素：">
                        <div v-for="(item,index) in form.rateFactor">
                            <el-select v-model="item.code" @change="handleChangeRate(item)" placeholder="请选择" clearable>
                                <el-option v-for="rule in ruleList" :key="rule.code" :label="rule.name"
                                           :value="rule.code">
                                </el-option>
                            </el-select>
                            <el-button v-if="index===form.rateFactor.length-1"
                                       @click="form.rateFactor.push({ code:'',name:'' })"
                                       type="text" icon="el-icon-plus" size="medium"></el-button>
                            <el-button v-if="index!==form.rateFactor.length&&form.rateFactor.length>1"
                                       @click="form.rateFactor.splice(index,1)"
                                       type="text" icon="el-icon-close" style="color: red" size="medium"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogForm = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit"
                       :loading="$store.getters.loadingBtn">
                确 定
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
    import { getRuleRuleList, getRuleCodeValue, addRuleList, editRuleList } from "@/api/balance/balance";
    import {maxLength,normalLength} from "@/utils/rules";

    export default {
        name: "ruleForm",
        props: {
            type: {
                type: String,
                default: 'fee'
            }
        },
        data() {
            return {
                dialogForm: false,
                isEdit: false,
                form: this.clearForm(),
                rules: {
                    feeRuleName:[{required:true,message:'请输入规则名称',trigger:'change'},normalLength],
                    businessModule:[{required:true,message:'请选择业务模式',trigger:'change'}],
                    feeUnit:[{required:true,message:'请选择计件指标',trigger:'change'}],
                    feeRule:[{required:true,message:'请选择计件条件',trigger:'change'}],
                },
                ruleList: [],
                isClick: true,
                loading: false,
            }
        },
        mounted() {
        },
        methods: {
            handleSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        console.log(this.form)
                        let data = {
                            ...JSON.parse(JSON.stringify(this.form)),
                            ruleType: 'piece'
                        }
                        data.feeRule.map(m => {
                            if (m.operator === 'in' || m.operator === 'nIn') {
                                m.typeValue = m.typeValue.toString()
                            }
                        })
                        this.isEdit ? this.handleEdit(data) : this.handleAdd(data)
                    } else {
                        this.$message({
                            message: '请检查表单',
                            type: 'error'
                        })
                    }
                })

            },
            handleAdd(data) {
                addRuleList(data).then(res => {
                    this.$message({ message: '新增成功!', type: 'success' })
                    this.dialogForm = false
                })
            },
            handleEdit(data) {
                editRuleList(data.id, data).then(res => {
                    this.$message({ message: '编辑成功!', type: 'success' })
                    this.dialogForm = false
                })
            },
            handleChangeModule() {
                this.form.feeRule.splice(0, this.form.feeRule.length)
                this.form.feeRule.push({
                    code: '',
                    operator: '',
                    typeValue: '',
                    dataSource: [],
                    ruleDataType: '',
                    isExistSub: 'AND'
                })
            },
            // 获取dataSource
            getSource(val) {
                this.loading=true
                if (val < this.form.feeRule.length) {
                    let params={search_EQ_code:this.form.feeRule[val].code}
                    getRuleCodeValue(params).then(res => {
                        this.form.feeRule[val].dataSource=res.data.aaData
                        this.getSource(val+1)
                    })
                }else{
                    this.loading=false
                }
            },
            // 因素改变
            handleChangeCode(item) {
                console.log(item)
                const params = {
                    search_EQ_code: item.code
                }
                getRuleCodeValue(params).then(res => {
                    item.typeValue = ''
                    if (item.operator === 'in' || item.operator === 'nIn') {
                        item.typeValue = []
                    }
                    this.ruleList.forEach((f, i) => {
                        if (f.code === item.code) {
                            item.ruleDataType = f.ruleDataType
                        }
                    })
                    if (item.dataSource) {
                        item.dataSource.splice(0, item.dataSource.length)
                    }
                    item.dataSource.push(...res.data.aaData)
                })
            },
            handleChangeOp(item, index) {
                let data = {
                    ...this.form.feeRule[index],
                    typeValue: ''
                }
                this.form.feeRule.splice(index, 1, data)
                console.log(this.form.feeRule)
                if (item.operator === 'in' || item.operator === 'nIn') {
                    this.isClick = false
                    let newData = {
                        ...this.form.feeRule[index],
                        typeValue: []
                    }
                    this.$nextTick(() => {
                        console.log(this.form.feeRule)
                        this.isClick = true
                        this.form.feeRule.splice(index, 1, newData)
                    })
                }
            },
            handleChangeRate(item) {
                this.ruleList.forEach(f => {
                    if (f.code === item.code) {
                        item.name = f.name
                    }
                })
            },
            getRule() {
                getRuleRuleList().then(res => {
                    this.ruleList = res.data.aaData
                })
            },
            clearForm() {
                return {
                    feeRuleName: "",
                    orgId: this.$store.getters.currentUser.org.id,
                    orgName: this.$store.getters.currentUser.org.name,
                    businessModule: "",
                    chargingMode: "STANDARD",
                    feeUnit: "",
                    rate: "",
                    feeRuleDesc: "",
                    feeRule: [{           // 计件条件
                        code: "",
                        operator: "",
                        typeValue: '',
                        dataSource: [],
                        ruleDataType: '',
                        isExistSub: 'AND',
                    }],
                    rateFactor: [{
                        name: "",
                        code: "",
                    }],
                }
            },
            getContent(item){
                console.log(item)
                let content=[]
                for (let i = 0; i < item.typeValue.length; i++) {
                    const el=item.typeValue[i]
                    item.dataSource.forEach(f=>{
                        if(el===f.code){
                            content.push(f.name)
                        }
                    })
                }
                return content.toString()
            }
        },
        computed: {
            title() {
                let [title, formType] = ['计件规则', '新增']
                if (this.type === 'fee') {
                    title = '计件规则'
                }
                if (this.isEdit) {
                    formType = '编辑'
                }
                return formType + title
            }
        },
        watch: {
            dialogForm(bool) {
                if (!bool) {
                    this.$parent.dialogForm = false
                    this.$emit('load')
                    this.$emit('clear')
                } else {
                    this.getRule()
                }
            }
        }
    }
</script>

<style scoped>

</style>
